﻿using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Batman.Cms.Domains;
using Batman.Cms.Services.Applications.Filters;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace Batman.Cms.Services.Applications
{
    public class ApplicationDataReader : ApplicationService
    {
        public IRepository<ApplicationData> applicationDataRepository { get; set; }

        /// <summary>
        /// 根据应用编号和应用数据编号查找出应用数据
        /// </summary>
        /// <param name="applicationId"></param>
        /// <param name="applicationDataId"></param>
        /// <returns>查询结果是个树状数据</returns>
        public ApplicationData Get(int applicationId, int applicationDataId)
        {
            var query = applicationDataRepository.GetAll().AsNoTracking().Where(t => t.ApplicationId == applicationId);

            query = query.Include(t => t.Children).ThenInclude(t => t.ApplicationDataItems);
            query = query.Include(t => t.ApplicationDataItems);
            var data = query.Where(t => t.Id == applicationDataId).ToList().FirstOrDefault();

            return data;
        }

        public PagedResultDto<ApplicationData> Get(PagedResultRequestDto page, ApplicationDataFilter filter)
        {
            var query = applicationDataRepository.GetAll().AsNoTracking();

            if (filter.IsDeleted.HasValue)
            {
                query = query.Where(t => t.IsDeleted == filter.IsDeleted);
            }
            if (filter.ApplicationId.HasValue)
            {
                query = query.Where(t => t.ApplicationId == filter.ApplicationId);
            }
            if (filter.HasParent.HasValue)
            {
                query = filter.HasParent == true ?
                    query.Where(t => t.ParentId.HasValue) :
                    query.Where(t => !t.ParentId.HasValue);
            }
            if (filter.ParentId.HasValue)
            {
                query = query.Where(t => t.ParentId == filter.ParentId);
            }
            var items = query.OrderByDescending(t => t.Id).Skip(page.SkipCount).Take(page.MaxResultCount).ToList();
            var total = query.Count();
            return new PagedResultDto<ApplicationData>(total, items);
        }

    }
}
